<?php
namespace app\index\controller;

use think\Controller;
use think\Db;
use think\Validate;
use think\Session;
use think\Request;
use think\Paginator;


class Classmate extends IndexController
{
	 function findClassmate($clid)
    {   
        // dump(session('web.uid'));die;
        $uid = session('web')['uid'];
      
        // dump($uid);die;
        //查询课程名称
        $classname = Db::name('myclass')->field('cname')->where('cid='.$clid)->find();
        $data = Db::name('classmate_selecttip')->where('clid='.$clid)->where('uid='.$uid)->find();
        // dump($uid);die;
        // dump($data);die;
        $invid = $data['inventid'];
        //查看是否为禁用状态
        if($data['state'] == 2){
            $this->error('你已经被禁用!');
        }
        //班级大家的互动信息
        $allchat = Db::name('eachmate_chat')->where('clid='.$clid)->order('createtime desc')->limit(6)->select();
        foreach($allchat as $k=>$v){
            $count = time() - $v['createtime']; 
            if($count < 60*60*24){
                $allchat[$k]['createtime'] = '刚才';
            }elseif($count >= 60*60*24 && $count <= 60*60*48){
                $allchat[$k]['createtime'] = '1天前';

            }else{
                 $allchat[$k]['createtime'] = '更早...';
            }
        }
        
        
        //当状态为1是 申请找同桌
        
        if($data['status'] == 1) {
            // dump($uid);die;
            //查询是否有邀请加入同坐
            $agr = Db::name('classmate_selecttip')->where('agreestatus = 1')->where('clid='.$clid)->where('uid='.$uid)->find(); 
            //如果有人请求加你为同桌进入此页面
            if($agr){
                $ask = Db::name('classmate_selecttip')->where('clid='.$clid)->where('inventid='.$uid)->find(); 
            // dump($ask);die;
                $rmate =Db::name('classmate_selecttip')->where('clid='.$clid)->where('uid='.$ask['uid'])->find();
                $nickname = Db::name('web_users')->where('id='.$ask['uid'])->find();
                $rmate['nickname'] = $nickname['nickname']; 
                  //清空缓存
                header("Cache-control: private");
                return view('classmate/confirmmate',['rmate'=>$rmate,'allchat'=>$allchat,'clid'=>$clid,'cname'=>$classname]);
            }

             $rmate = Db::name('classmate_selecttip')
                ->where('status',1)
                ->where('uid','neq',$uid)
                ->where('clid='.$clid)
                ->where('ageset='.$data['ageset'].' or sexset='.$data['sexset'].' or jobset='.$data['jobset'].' or gradeset='.$data['gradeset'])
                ->select();
            // dump($rmate);die;
             $num = count($rmate);       
            // //查询符合已经在申请同桌匹配条件的用户
            // $rmate = Db::name('classmate_selecttip')
            //         ->where('status',1)
            //         ->where('ageset',$data['ageset'])
            //         ->where('sexset',$data['sexset'])
            //         ->whereor('jobset',$data['jobset'])
            //         ->whereor('gradeset',$data['gradeset'])
            //         ->where('uid','neq',$uid)
            //         // ->order('inventid desc')
            //         ->select();
            foreach($rmate as $k=>$v){
                $nickname = Db::name('web_users')->where('id='.$v['uid'])->find();
                $rmate[$k]['nickname'] = $nickname['nickname'];
            }

            // dump($rmate);die;
            $num = count($rmate);
            //清空缓存
            header("Cache-control: private");

            return view('classmate/selmate',['rmate'=>$rmate,'num'=>$num,'clid'=>$clid,'invid'=>$invid,'allchat'=>$allchat,'cname'=>$classname]);
        }

        //互为同桌 获取同住之间发送信息 遍历到页面
        if ($data['status'] == 2) {

            $nickname = session('web')['nickname'];
            $uid = session('web')['uid'];
            //查询我的信息
            $eachdata = Db::name('classmate_selecttip')->where('clid='.$clid)->where('uid ='.$uid)->find();
            
            //查询同桌的信息
            $mateinfo = Db::name('classmate_selecttip')->where('clid='.$clid)->where('uid ='.$eachdata['inventid'])->find();
            $touidname = Db::name('web_users')->where('id='.$eachdata['inventid'])->find();
            $mateinfo['face'] = $touidname['face'];
            $datachat = Db::name('eachmate_chat')
                    ->where('clid='.$clid)
                    ->where('uid='.$uid)
                    ->whereor('uid='.$eachdata['inventid'])
                    ->order('createtime desc')
                    // ->limit(3)
                    ->paginate(1);
                    // dump($datachat);
                    $redatachat=$datachat->all();

            // print_r($datachat);die;  
            foreach($redatachat as $k=>$v){
                $count = time() - $v['createtime']; 
                    if($count < 60*60*24){
                    $redatachat[$k]['createtime'] = '刚才';
                }elseif($count >= 60*60*24 && $count <= 60*60*48){
                    $redatachat[$k]['createtime'] = '1天前';

                }else{
                    $redatachat[$k]['createtime'] = '更早...';
                }
            }
            $page=$datachat->render();

            // dump($page);die;
        //查询消息有没有状态为1的新消息
        $news = Db::name('eachmate_chat')->where('clid='.$clid)->where('touid',$uid)->where('news','1')->find();    
               // dump($mateinfo);die;
                 //清空缓存
            header("Cache-control: private");
            return view('classmate/yesmate',['datachat'=>$redatachat,'uid'=>$uid,'allchat'=>$allchat,'nickname'=>$nickname,'touidname'=>$touidname['nickname'],'eachdata'=>$eachdata,'news'=>$news,'cname'=>$classname,'mateinfo'=>$mateinfo,'clid'=>$clid,'page'=>$page]);
        }

        if ($data['status'] == 0){ 
            // dump($clid);die;
            $rmate = Db::name('classmate_selecttip')->where('clid ='.$clid)->where('status = 0' )->where('uid','neq',$uid)->find();
           // dump($rmate);die;
            if ($rmate){
                $nickname = Db::name('web_users')->where('id='.$rmate['uid'])->find();
                $rmate['nickname'] = $nickname['nickname'];
                  //清空缓存
            header("Cache-control: private");
            
            // dump($token);die;
            return view('classmate/classmate',['rmate'=>$rmate,'allchat'=>$allchat,'clid'=>$clid,'cname'=>$classname]);
            } else {
                  //清空缓存
            header("Cache-control: private");

            ;
             // dump($token);die;
             return view('classmate/classmate',['rmate'=>$rmate,'allchat'=>$allchat,'clid'=>$clid,'cname'=>$classname]);
                
            }
            
        }
       

    }
    function selectTip()
    {
        //清空缓存
        header("Cache-control: private");
        return view('classmate/selecttip');
    }
    function doSelecttip()
    {
        
        $data = input('post.');
        $clid = $data['clid'];
        //设置验证 是否为页面重复提交或刷新 通过比对本次的提交数据和 上次存入session的数据是否相同
        $ch = implode($data);
        $check =md5($ch);
        // dump($check);dump('token:'.session('seltoken'));die;
        if($check == session('seltoken')){
              // dump($check);dump('bb'.session('seltoken'));die;
            return $this->findClassmate($clid);
        }
        session('seltoken',$check);
        session('ovtoken','');
        session('patoken','');
        // dump($check);dump('token:'.session('token'));die;
        // dump($data);die;
        // if($data['token']==session('token')){
        //   return $this->findClassmate($clid);  
        // }
        // dump($clid);die;
        //查询最新大家互动信息
         $allchat = Db::name('eachmate_chat')->where('clid='.$clid)->order('createtime desc')->limit(6)->select();
        foreach($allchat as $k=>$v){
            $count = time() - $v['createtime']; 
            if($count < 60*60*24){
                $allchat[$k]['createtime'] = '刚才';
            }elseif($count >= 60*60*24 && $count <= 60*60*48){
                $allchat[$k]['createtime'] = '1天前';

            }else{
                 $allchat[$k]['createtime'] = '更早...';
            }
        }
        // dump($allchat);die;
        
        //接收选择同桌条件 和自己信息的设置
        $uid = session('web')['uid'];
        $find = Db::name('classmate_selecttip')->where('clid='.$clid)->where('uid='.$uid)->find();
        if ($find['agreestatus'] == 1){
             return $this->findclassmate($clid);
        }
        Db::name('classmate_selecttip')->where('clid='.$clid)->where('uid='.$uid)->delete();
        $nickname = session('web')['nickname'];
        $data['uid'] = $uid;
        $data ['clid'] = $clid;
        $data['status'] = 1;
        $data['saycontent'] = strip_tags($data['saycontent']);
        $data['mycontent'] = strip_tags($data['mycontent']);
        //过滤敏感字
        $data['saycontent'] = $this->checkword($data['saycontent']);
        $data['mycontent'] = $this->checkword($data['mycontent']);
        $res = Db::name('classmate_selecttip')->insert($data);



        //选择符合条件的人过滤掉自己
        //
        
        $rmate = Db::name('classmate_selecttip')
                ->where('status',1)
                ->where('clid='.$clid)
                ->where('uid','neq',$uid)
                ->where('ageset='.$data['ageset'].' or sexset='.$data['sexset'].' or jobset='.$data['jobset'].' or gradeset='.$data['gradeset'])
                ->select();
        // echo Db::name('classmate_selecttip')->getlastsql();
        foreach($rmate as $k=>$v){
        	$nickname = Db::name('web_users')->where('id='.$v['uid'])->find();
        	$rmate[$k]['nickname'] = $nickname['nickname'];
        }
        //设置一个表示避免刷新重复提交
        // session('token',rand(100000,9999999));
        // $token = session('token');
        $num = count($rmate);
        // dump($num);die;
        return $this->findClassmate($clid);
        
        // dump($rmate);die;
        //没有申请同桌的进入后invid 设置为空
        // return view('classmate/selmate',['rmate'=>$rmate,'num'=>$num,'invid'=>'','allchat'=>$allchat]);
    }

    function nomate()
    {
        //清空缓存
        header("Cache-control: private");
    	return view('classmate/nomate');
    }

    function yesmate()
    {
          //清空缓存
        header("Cache-control: private");
        return view('class/yesmate');
    }
    function invent()
    {
        // return 8888888899999;
        $data= input('post.');
        // return $data;
        $clid =$data['clid'];
        $uid = session('web')['uid'];
        //将被邀请用户uid写入inventid
        $arr = ['inventid' =>$data['uid']];
        //查询登录用户的状况
        $res = Db::name('classmate_selecttip')->where('clid='.$clid)->where('uid='.$uid)->find();
        //如果本人已经收到邀请不能在进行 邀请同桌操作
        if ($res['agreestatus'] == 1){
            return 3;
        }
        //如果没有邀请inventid 就写入对方uid
        if ($res['inventid'] != $data['uid']){
            $sel = Db::name('classmate_selecttip')->where('uid='.$uid)->where('clid='.$clid)->update($arr);
            //将被邀请人调整为等待批准状态
            $newarr = ['agreestatus'=>1];
            Db::name('classmate_selecttip')->where('uid='.$data['uid'])->where('clid='.$clid)->update($newarr);
            return 0;
        } else {
            //有邀请inventid 就更换为0
            $arr = ['inventid' => 0];
            $sel = Db::name('classmate_selecttip')->where('uid='.$uid)->where('clid='.$clid)->update($arr);
            //更换批准状态
            $newarr = ['agreestatus'=>0];
            Db::name('classmate_selecttip')->where('uid='.$data['uid'])->where('clid='.$clid)->update($newarr);
            return 1;
        }
    }
    function passmate($uid,$clid)
    {   
        $landuid = session('web')['uid'];

        $check =md5($uid.$clid);
              // dump($check);dump('patoken:'.session('patoken'));die;

        if($check == session('patoken')){
              // dump($check);dump('patoken:'.session('patoken'));die;
            return $this->findClassmate($clid);
        }
        session('patoken',$check);
        

        //传过来的$uid 为被邀请人的uid
        //本登录用户
        // dump($uid);die;
        //将本登录用户同桌status改为2
        $uparr = ['inventid'=>$landuid,'status'=>2];
        $data = Db::name('classmate_selecttip')->where('uid='.$uid)->where('clid='.$clid)->update($uparr);
        //将被邀请的互为同桌用户status改为2
        $datearr = ['inventid'=>$uid,'status'=>2];
        $data = Db::name('classmate_selecttip')->where('uid='.$landuid)->where('clid='.$clid)->update($datearr); 
        return $this->findClassmate($clid);
    }
    function refusemate($uid,$clid)
    {


        $landuid = session('web')['uid'];
        $check =md5($landuid.$clid);
              // dump($check);dump('retoken:'.session('retoken'));die;
        if($check == session('retoken')){
            return $this->findClassmate($clid);
        }
        session('retoken',$check);
        session('seltoken','');

        //$uid 为发起邀请人uid
        //删除发起邀请人的 inventid 
        $arr = ['inventid'=>0];
        Db::name('classmate_selecttip')->where('uid ='.$uid)->where('clid='.$clid)->update($arr);
        //修改被邀请人的 agreestatus状态
        $newarr = ['agreestatus'=>0];
        Db::name('classmate_selecttip')->where('uid ='.$landuid)->where('clid='.$clid)->update($newarr);

        return $this->findclassmate($clid);
    }
    function canclemate()
    {   
        //取消邀请同桌
        $uid = session('web')['uid'];
        $clid = cache('cid');
        $change = ['status'=>0,'inventid'=>0,'friendid'=>0]; 
        $data = Db::name('classmate_selecttip')->where('uid='.$uid)->where('clid='.$clid)->update($change);
          //清空缓存
        header("Cache-control: private");
        return view('classmate/classmate');
    }
    function matechat()
    {
        //接收页面互动信息传入数据库
        $data = input('post.');
        $clid = $data['clid'];
        $uid = session('web')['uid'];
        $data['uid'] = $uid;
        //查询同桌的inventid,传入data数组准备插入
        $eachdata = Db::name('classmate_selecttip')->where('clid='.$clid)->where('uid ='.$uid)->find();
        $data['touid'] = $eachdata['inventid'];
        $data['createtime'] = time();
        //查询昵称
        $nickname = Db::name('web_users')->where('id ='.$uid)->find();
        $touidname = Db::name('web_users')->where('id ='.$eachdata['inventid'])->find();
        $data['nickname'] = $nickname['nickname'];
        $data['touidname'] = $touidname['nickname'];
        if($data['type'] == 3){
            $data['text'] = $this->checkword($data['text']);
        }
        //设置新的互动信息状态为1
        $data['news'] = 1;
        //插入一条互动信息
        $res = Db::name('eachmate_chat')->insert($data);
        if($res){
            return 'ok';
        }
        
    }
     public function checkword($str)
    {
         //过滤敏感词
        $arr = ['鸡', '你妹', '你大爷', 'SB','傻逼','民主','共和','共'];
        foreach($arr as $v){
            // 统计$v的原子个数
            $num = preg_match_all('/./u', $v);
            // 重复 * 出现 num次
            $star = str_repeat('*', $num);
            $preg = "/{$v}/";
            // $str = preg_replace($preg, '*', $str);
            $str = preg_replace($preg, '<span style="color:red;">'.$star.'</span>'   , $str);
        }
        return $str;
    }
    function overmate($clid)
    {
        //解除同桌关系

        //删除发起邀请人的 inventid 
        $landuid = session('web')['uid'];
        $check =md5($landuid.$clid);
              // dump($check);dump('ovtoken'.session('ovtoken'));die;
        if($check == session('ovtoken')){
            return $this->findClassmate($clid);
        }
        session('ovtoken',$check);
        session('seltoken','');
        session('patoken','');

        //修改同桌人的 状态
        //查询被邀请人的uid
        $inventid = Db::name('classmate_selecttip')->where('clid='.$clid)->where('uid ='.$landuid)->find();
        $newarr =  ['inventid'=>0,'status'=>1,'agreestatus'=>0];
        Db::name('classmate_selecttip')->where('uid ='.$inventid['inventid'])->where('clid='.$clid)->update($newarr);

        //改变登录本人的状态
        $arr = ['inventid'=>0,'status'=>1,'agreestatus'=>0];
        Db::name('classmate_selecttip')->where('uid ='.$landuid)->where('clid='.$clid)->update($arr);

        //删除互动内容
        Db::name('eachmate_chat')->where('uid='.$landuid)->whereor('uid='.$inventid['inventid'])->where('clid='.$clid)->delete();

        return $this->findclassmate($clid);
    }
    function messagemate ($clid)
    {   
        //查询课程名称
        $classname = Db::name('myclass')->field('cname')->where('cid='.$clid)->find();
        //班级大家的互动信息
        $allchat = Db::name('eachmate_chat')->order('createtime desc')->where('clid='.$clid)->limit(6)->select();
        foreach($allchat as $k=>$v){
            $count = time() - $v['createtime']; 
            if($count < 60*60*24){
                $allchat[$k]['createtime'] = '刚才';
            }elseif($count >= 60*60*24 && $count <= 60*60*48){
                $allchat[$k]['createtime'] = '1天前';

            }else{
                 $allchat[$k]['createtime'] = '更早...';
            }
        }

        //同桌互动消息
        $nickname = session('web')['nickname'];
        $uid = session('web')['uid'];
        $eachdata = Db::name('classmate_selecttip')->where('clid='.$clid)->where('uid ='.$uid)->find();
        $touidname = Db::name('web_users')->where('id='.$eachdata['inventid'])->find();
        $datachat = Db::name('eachmate_chat')->where('uid='.$uid)->where('clid='.$clid)->whereor('uid='.$eachdata['inventid'])->order('createtime desc')->select(); 
        //调整时间名称 
        foreach($datachat as $k=>$v){
            $count = time() - $v['createtime']; 
                if($count < 60*60*24){
                $datachat[$k]['createtime'] = '刚才';
            }elseif($count >= 60*60*24 && $count <= 60*60*48){
                $datachat[$k]['createtime'] = '1天前';

            }else{
                $datachat[$k]['createtime'] = '更早...';
            }
        }
        
        //点击查看后修改消息状态
        $changenews = ['news'=>0];
        Db::name('eachmate_chat')->where('touid',$uid)->where('clid='.$clid)->update($changenews);
           //清空缓存
        header("Cache-control: private");      
        return view('classmate/messagemate',['datachat'=>$datachat,'uid'=>$uid,'allchat'=>$allchat,'cname'=>$classname,'clid'=>$clid]);

    }
    function ajaxmessage()
    {
        $clid = cache('cid');
        $ajaxback = Db::name('eachmate_chat')->where('clid='.$clid)->where('touid',$uid)->where('news',1)->find();

        if ($ajaxback) {
            return '200';
        }else {
            return '400';
        }
    }

    


}